package com.gzz.orchid.common.webmvc.securityjwt;

import com.gzz.orchid.common.webmvc.support.HttpResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 认证接口
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/authentic")
public class AuthenticationApi {
    private final AuthenticationManager authenticationManager;

    /**
     * 登录
     */
    @Validated
    @RequestMapping("/login")
    public HttpResult login(LoginModel model) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(model.getUsername(), model.getPassword());
        Authentication authentication = authenticationManager.authenticate(token);
        User user = (User) authentication.getPrincipal();
        log.info("用户登录: {}", user.getUsername());
        return HttpResult.success();
    }

    /**
     * 登出
     */
    @RequestMapping("/logout")
    public HttpResult logout() {
        return HttpResult.success();
    }
}
